package parsers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class ParserPruebaIEEEXplore {

	/**
	 * 
	 * 
	 * */

	public static void main(String[] args) {
		String bibGeneral = "%archivo ieexplore%\n";
		File fil = new File("busquedasIEEEXplore/");
		System.out.println(fil.getAbsolutePath());
		File[] archivos = fil.listFiles();
		for (int iteracion = 0; iteracion < archivos.length; iteracion++) {
			try {
				String[] lineasHTML = null;
				lineasHTML = cargarURLAsLines("file:///"
						+ archivos[iteracion].getAbsolutePath());
				// System.out.println(lineasHTML);
				System.out.println("----------------- Inicio -");
				bibGeneral += convertoToBib(lineasHTML);
				System.out.println("----------------- Fin    -");
				// System.out.println(bibContent);
			} catch (IOException e2) {
				System.out.println(e2);
				e2.printStackTrace();
			}
		}
		try {
			guardarArchivo(bibGeneral);
		} catch (Exception e) {
			System.out.println("error al guardar archivo");
			e.printStackTrace();
		}
	}

	public static String[] cargarURLAsLines(String dir) throws IOException {
		URL url = new URL(dir);
		URLConnection spoof;
		spoof = url.openConnection();
		// Spoof the connection so we look like a web browser
		spoof.setRequestProperty("User-Agent",
				"Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0;    H010818)");
		BufferedReader in;
		in = new BufferedReader(new InputStreamReader(spoof.getInputStream()));
		String strLine = "";

		List<String> lineas = new ArrayList<String>();
		while ((strLine = in.readLine()) != null) {
			// finalHTML += strLine;
			lineas.add(strLine);
		}
		String[] finalHTML = new String[lineas.size()];
		in.close();
		lineas.toArray(finalHTML);
		return finalHTML;
	}

	public static String convertoToBib(String[] lineas) throws IOException {
		int cantidadDeErrores = 0;
		int cantidadDeAciertos = 0;
		String cvsSplitBy = "\",\"";
		String bibGlobal = "";
		for (int i = 2; i < lineas.length; i++) {
			lineas[i] = lineas[i].trim();
			String[] parts = lineas[i].split(cvsSplitBy);

			for (int j = 0; j < parts.length; j++) {
				System.out.println("[" + j + "]" + parts[j]);
			}

			ArrayList<String> test = new ArrayList<String>();
			for (int j = 0; j < parts.length; j++) {
				String base = parts[j];
				if (!(base.startsWith(","))) {
					test.add(parts[j]);
				}
			}
			parts = new String[test.size()];
			for (int j = 0; j < test.size(); j++) {
				parts[j] = test.get(j);
			}

			/**
			 * [0] [1] Document Title [2] ,Authors, [3] Author Affiliations [4]
			 * Publication Title [5] Publication Date [6] Publication Year [7]
			 * Volume [8] Issue [9] Start Page [10] End Page [11] Abstract [12]
			 * ISSN [13] ISBN [14] EISBN [15] DOI [16] ,PDF Link, [17] Author
			 * Keywords [18] IEEE Terms [19] INSPEC Controlled Terms [20] INSPEC
			 * Non-Controlled Terms [21] DOE Terms [22] PACS Terms [23] MeSH
			 * Terms [24] ,Article Citation Count,Patent Citation Count, [25]
			 * Reference Count [26] Copyright Year [27] Online Date [28] ,Date
			 * Added To Xplore, [29] Meeting Date [30] Publisher [31] Sponsors
			 * [32] ,Document Identifier
			 */

			try {
				bibGlobal += crearBib(parts);

				/*
				 * System.out.println(i +
				 * " ************* nuevo item ************** \n");
				 * System.out.println("item title: " + parts[1]);
				 * System.out.println("publication title: " + parts[4]);
				 * System.out.println("Journal volume: " + parts[7]);
				 * System.out.println("Journal issue: " + parts[8]);
				 * System.out.println("Item DOI: " + parts[15]);
				 * System.out.println("Authors: " + parts[2]);
				 * System.out.println("Year: " + parts[6]);
				 * System.out.println("URL: " + parts[16]);
				 * System.out.println("abstract: " + parts[11]);
				 * System.out.println("ISBN: " + parts[13]);
				 * System.out.println("------------------------------------\n");
				 */
				cantidadDeAciertos++;

			} catch (Exception e) {
				System.err.print("se presento un problema en el item: " + i + " -> ");
				System.err.println(e);
				cantidadDeErrores++;
				break;
			}

		}// for;
		System.out.println("Correctos: " + cantidadDeAciertos);
		System.out.println("Fallidos: " + cantidadDeErrores);
		return bibGlobal;
	} // metodo convertir

	private static String crearBib(String[] parts) throws IOException {

		String bib = "";
		String tag = "" + parts[14];
		String tipo = seleccionarTipo(parts);
		/*
		 * if(tag.contains("and the iterative or the")){ for (int i = 0; i <
		 * parts.length; i++) { System.out.println(i+" : "+parts[i]); } }
		 */
		try {
			bib += "\n@" + tipo + "{" + tag + ",";
			bib += "author = {" + parts[1] + "},";
			bib += "title = {{" + parts[0] + "}},";
			bib += "venue = {" + parts[3] + "},";
			bib += "doi = {" + parts[14] + "},";
			bib += "url = {" + parts[15] + "},";
			bib += "year = {" + parts[5] + "},";
			bib += "abstract = {" + parts[10] + "}}";
		} catch (Exception e) {
			System.err.println("error: " + e);
		}
		return bib;
	} // metodo

	private static String seleccionarTipo(String[] parts) {
		String retorno = "ARTICLE";
		if (parts[parts.length-1].contains("IEEE Conference Publications")) {
			retorno = "INPROCEEDINGS";
		}
		if (parts[parts.length-1].contains("IEEE Early Access Articles")) {
			retorno = "ARTICLE";
		}
		if (parts[parts.length-1].contains("IEEE Journals & Magazines")) {
			retorno = "ARTICLE";
		}
		if (parts[parts.length-1].contains("IEEE Standards")) {
			retorno = "ARTICLE";
		}
		if (parts[parts.length-1].contains("IET Conference Publications")) {
			retorno = "INPROCEEDINGS";
		}
		if (parts[parts.length-1].contains("IET Journals & Magazines")) {
			retorno = "INPROCEEDINGS";
		}
		if (parts[parts.length-1].contains("Wiley-IEEE Press eBook Chapters")) {
			retorno = "chapter";
		}
		return retorno;
	}

	public static void guardarArchivo(String bib) throws IOException {
		File f = new File("salidaLibreriaIEEEXplore.bib");
		FileWriter salida = new FileWriter(f);
		salida.write(bib);
		salida.flush();
		salida.close();
		System.out.println("Archivo Guardado -----------------");
	}

} // clase
